public class HashBuck {

    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    //负载因子
    public static final float LOAD_FACTOR = 0.75F;

    public int usedSize;

    public Node[] array;

    public HashBuck() {
        array = new Node[10];
    }

    public void push(int key,int val) {
        int index = key % array.length;

        //判断 key 是否被存储过, 存储过则更新 val 的值
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;  //更新 val 的值
                return;
            }
            cur = cur.next;
        }

        //头插法插入
        Node newNode = new Node(key, val);
        newNode.next = array[index];
        array[index] = newNode;

        usedSize++;

        //如果负载因子超出范围, 则进行扩容
        if (calcLoadFactor() >= LOAD_FACTOR) {
            resize();
        }

    }

    //扩容
    private void resize() {
        Node[] newArray = new Node[array.length*2];

        //扩容后, 需要重新遍历数组当中的每个链表
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];

            while (cur != null) {
                int newIndex = cur.key % newArray.length;

                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = cur.next;
            }
        }
        array = newArray;

    }



    private float calcLoadFactor() {
        return usedSize*1.0F / array.length;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

}
